using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class DialogueManager : Singleton<DialogueManager>
{
    [SerializeField] private GameObject dialoguePanel;
    [SerializeField] private Image npcIcon;
    [SerializeField] private TextMeshProUGUI npcNameTMP;
    [SerializeField] private TextMeshProUGUI npcDialogueTMP;

    public NPCInteraction NPCSelected { get; set; }

    private bool dialogueStarted;
    private PlayerActions actions;
    private Queue<string> dialogueQueue = new Queue<string>();

    protected override void Awake()
    {
        base.Awake();
        actions = new PlayerActions();
    }

    private void Start()
    {
        actions.Dialogue.Interact.performed += ctx => ShowDialogue();
        actions.Dialogue.Continue.performed += ctx => ContinueDialogue();
    }

    public void CloseDialoguePanel()
    {
        if (dialoguePanel == null)
        {
            Debug.LogWarning("Dialogue panel has been destroyed or is missing.");
            return;
        }

        dialoguePanel.SetActive(false);
        dialogueStarted = false;
        dialogueQueue.Clear();
    }

    private void LoadDialogueFromNPC()
    {
        if (NPCSelected == null || NPCSelected.DialogueToShow == null || NPCSelected.DialogueToShow.Dialogue.Length <= 0)
            return;

        foreach (string sentence in NPCSelected.DialogueToShow.Dialogue)
        {
            dialogueQueue.Enqueue(sentence);
        }
    }

    private void ShowDialogue()
    {
        if (NPCSelected == null || NPCSelected.DialogueToShow == null)
            return;

        if (dialogueStarted)
            return;

        if (dialoguePanel == null)
        {
            Debug.LogWarning("Dialogue panel is missing.");
            return;
        }

        dialoguePanel.SetActive(true);
        LoadDialogueFromNPC();

        if (npcIcon != null)
            npcIcon.sprite = NPCSelected.DialogueToShow.Icon;

        if (npcNameTMP != null)
            npcNameTMP.text = NPCSelected.DialogueToShow.Name;

        if (npcDialogueTMP != null)
            npcDialogueTMP.text = NPCSelected.DialogueToShow.Greeting;

        dialogueStarted = true;
    }

    private void ContinueDialogue()
    {
        if (NPCSelected == null)
        {
            dialogueQueue.Clear();
            CloseDialoguePanel();
            return;
        }

        if (dialogueQueue.Count <= 0)
        {
            CloseDialoguePanel();
            dialogueStarted = false;
            return;
        }

        if (npcDialogueTMP != null)
            npcDialogueTMP.text = dialogueQueue.Dequeue();
    }

    private void OnEnable()
    {
        actions?.Enable();
    }

    private void OnDisable()
    {
        actions?.Disable();
    }
}
